﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.IO;
using System.Reflection;

namespace DTBuilderLib
{
    /// <summary>
    /// Class to get at external program paths. Just puts all of this in one place so
    /// crazy logic to locate things doesn't need to be here.
    /// </summary>
    public class ExternalToolLocations
    {

        /// <summary>
        /// Loads the default locations of all external tools.
        /// </summary>
        public static void LoadDefaultLocations()
        {
            CacheGS();
            CacheTemplateLoc();
            CacheWebViewer();
        }

        /// <summary>
        /// return the location of the console version of ghostscript.
        /// </summary>
        /// <returns></returns>
        public static string LocationGS
        {
            get { CacheGS(); return _gs; }
            set { _gs = value; }
        }

        /// <summary>
        /// Returns the location of the viewer.
        /// </summary>
        public static string LocationWebViewer
        {
            get { CacheWebViewer(); return _viewer; }
            set { _viewer = value; }
        }

        /// <summary>
        /// Find the ghost script location.
        /// </summary>
        private static void CacheGS()
        {
            if (_gs != null)
            {
                return;
            }

            using (RegistryKey k = Registry.LocalMachine.OpenSubKey("SOFTWARE\\GPL Ghostscript"))
            {
                if (k == null)
                {
                    ///
                    /// Last ditch effort to find things if the registry doesn't show us where it is... this is really fishing in the dark...
                    /// 

                    DirectoryInfo info = new DirectoryInfo(System.Environment.ExpandEnvironmentVariables(@"%SystemDrive%\Program Files\gs"));
                    if (info.Exists) {
                        foreach (DirectoryInfo subdir in info.GetDirectories()) {
                            FileInfo gs = new FileInfo(subdir.FullName + @"\bin\gswin32c.exe");
                            if (gs.Exists) {
                                _gs = gs.FullName;
                                return;
                            }
                        }
                    }

                    ///
                    /// No luck!
                    /// 

                    throw new DTException("Could not find ghost script registry key!");
                }
                foreach (var key in k.GetSubKeyNames())
                {
                    using (RegistryKey gsloc = k.OpenSubKey(key))
                    {
                        if (gsloc != null)
                        {
                            _gs = (string) gsloc.GetValue("GS_DLL");
                            if (_gs != null)
                            {
                                _gs = _gs.Substring(0, _gs.LastIndexOf("\\") + 1) + "gswin32c.exe";
                                return;
                            }
                        }
                    }
                }
            }

        }

        /// <summary>
        /// Hold onto the internal location of ghost script's executable.
        /// </summary>
        private static string _gs = null;

        /// <summary>
        /// Returns the Silver Light project files that we are going to use to build
        /// the final web site.
        /// </summary>
        public static string LocationSLTemplateControl
        {
            get
            {
                CacheTemplateLoc();
                return _templateLoc;
            }
            set { _templateLoc = value; }
        }

        /// <summary>
        /// Holds the internal location of the various files.
        /// </summary>
        private static string _templateLoc = null;

        /// <summary>
        /// Finds the location of the templates
        /// </summary>
        private static void CacheTemplateLoc()
        {
            if (_templateLoc != null)
            {
                return;
            }

            /// Development Code is BAD... but...
            _templateLoc = @"..\..\..\DeepTalkDisplay\ClientBin";
            if (Directory.Exists(_templateLoc))
            {
                return;
            }

            /// Perhaps next to the current executable (from an install)?
            _templateLoc = Assembly.GetCallingAssembly().Location;
            _templateLoc = _templateLoc.Substring(0, _templateLoc.LastIndexOf('\\'));
            _templateLoc += "\\SLViewerTemplate";
            if (!Directory.Exists(_templateLoc))
            {
                throw new DTException("Could not find the template files for the SilverLight control. Expected them in SLViewerTemplate");
            }
        }

        /// <summary>
        /// Location of the web viewer program.
        /// </summary>
        private static string _viewer = null;

        private static void CacheWebViewer()
        {
            if (_viewer != null)
            {
                return;
            }

            ///
            /// Development code is never good, but this makes it possible to actually use this!
            /// 

            FileInfo inf = new FileInfo(@"..\..\..\DeepTalkClientWebServer\bin\Debug\DeepTalkClientWebServer.exe");
            if (inf.Exists)
            {
                _viewer = inf.FullName;
                return;
            }

            ///
            /// Ok -- had better hope it is in the right place then!
            /// 

            _viewer = Assembly.GetCallingAssembly().Location;
            _viewer = _templateLoc.Substring(0, _templateLoc.LastIndexOf('\\'));
            _viewer += "\\Web Viewer\\DeepTalkClientWebServer.exe";
        }
    }
}
